import os
from urllib.parse import unquote

import aiofiles
import falcon
import App_setting as setting
from WebBackend.dataclass.Directory import path_is_valid
from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.store.TaskStore import TaskStore
from WebBackend.utils import mylog


@falcon.before(login_require)
class FileOperationAPI:
    def __init__(self, task_store: TaskStore):
        self.task_store = task_store

    async def on_post(self, req: falcon.Request, resp: falcon.Response):
        action = req.params.get('action')
        if action == 'pack':
            data: dict = await req.media
            pack_method: str = data.get('pack_method')
            pack_name: str = data.get('pack_name')
            parent_path: str = data.get('parent')
            task_id: str = data.get('task_id')
            file_list: list[dict] = data.get('file_list')
            if not path_is_valid(parent_path):
                raise falcon.HTTPNotAcceptable(title='目录不合法')
            if pack_method not in command_map.keys():
                raise falcon.HTTPNotAcceptable(title="打包方式不合法")

            if '/' in pack_name or '\\' in pack_name:
                if not path_is_valid(pack_name):
                    raise falcon.HTTPNotAcceptable(title='打包目的地不合法')
            else:
                pack_name = os.path.join(parent_path, pack_name)
            if not pack_name.endswith(('.zip', '.tar.gz', 'tar')):
                raise falcon.HTTPNotAcceptable(title="打包文件拓展名不合法")
            cmd1 = command_map.get(pack_method, 'tar -cf')
            cmd2 = pack_name
            cmd3 = [f"{os.path.join(parent_path, item['path_name'])}" for item in file_list]
            cmd = f"{cmd1} {cmd2} {' '.join(cmd3)}"
            #print(cmd)
            await self.task_store.create_task(command=cmd, task_id=task_id)
            await self.task_store.start_task(task_id)

            resp.media = data


command_map = {
    'pack': 'tar -cf',
    'pack+zip1': 'tar --use-compress-program="gzip -1" -cf',
    'pack+zip2': 'tar --use-compress-program="gzip -2" -cf',
    'pack+zip3': 'tar --use-compress-program="gzip -3" -cf',
    'pack+zip4': 'tar --use-compress-program="gzip -4" -cf',
    'pack+zip5': 'tar --use-compress-program="gzip -5" -cf',
    'pack+zip6': 'tar -czf',
    'pack+zip7': 'tar --use-compress-program="gzip -7" -cf',
    'pack+zip8': 'tar --use-compress-program="gzip -8" -cf',
    'pack+zip9': 'tar --use-compress-program="gzip -9" -cf',
}
